<template>
  <div class="app-container">
    <Form
      :model="formState"
      autocomplete="off"
      :label-col="labelCol"
      :rules="rules"
      @finish="onSubmit"
    >
      <FormItem label="文件">
        <Upload
          name="file"
          :headers="headers"
          action="/basic-api/file/sysFile/upload"
          @change="handleChange"
        >
          <Button type="primary" :loading="uploadLoading">上传</Button>
          <template #itemRender></template>
        </Upload>
      </FormItem>

      <FormItem label="备注" name="remark">
        <Input v-model:value="formState.remark" allow-clear placeholder="备注" />
      </FormItem>
      <FormItem label="连接" name="link">
        <Input v-model:value="formState.link" allow-clear placeholder="连接" />
      </FormItem>
      <FormItem label="连接类型" name="link">
        <Select v-model="formState.linkType" allow-clear placeholder="连接类型">
          <SelectOption value="1">H5</SelectOption>
          <SelectOption value="2">小程序</SelectOption>
        </Select>
      </FormItem>

      <FormItem>
        <a-button type="primary" html-type="submit" :loading="btnLoading">提交</a-button>
      </FormItem>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import {
    Form,
    FormItem,
    Input,
    message,
    Upload,
    Button,
    Select,
    SelectOption,
  } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { add } from '/@/api/carousel'
  import { getToken } from '/@/utils/auth'

  const emit = defineEmits(['onSuccess'])

  const labelCol = { style: { width: '80px' } }

  const rules: Record<string, Rule[]> = {
    remark: [{ required: true, trigger: 'change', message: '名称不能为空' }],
    url: [{ required: true, trigger: 'change', message: '权限标识不能为空' }],
  }

  const formState = ref({
    remark: '',
    link: '',
    linkType: '',
    url: '',
  })

  const btnLoading = ref(false)

  const onSubmit = () => {
    btnLoading.value = true
    add(formState.value)
      .then(() => {
        btnLoading.value = false
        emit('onSuccess')
      })
      .catch(() => (btnLoading.value = false))
  }

  const uploadLoading = ref(false)
  const headers = {
    Authorization: `Bearer ${getToken()}`,
  }
  const handleChange = (info) => {
    uploadLoading.value = true
    if (info.file.status !== 'done') {
      return
    }
    if (info.file.response.code === 200) {
      uploadLoading.value = false
      message.success('上传成功')
      formState.value.url = info.file.response.data.url
    } else {
      uploadLoading.value = false
      message.error(info.file.response.message)
    }
  }
</script>
